using System;
using Caliburn.Micro;
using TimeKeeper.Infrastructure;

namespace TimeKeeper.Results
{
    public class FactoryDialogResult<T> : IResult where T : Screen
    {
        private readonly IViewModelFactory<T> _viewModelFactory;
        private readonly Action<T> _initialization;

        public FactoryDialogResult(IViewModelFactory<T> viewModelFactory, Action<T> initialization)
            : this(viewModelFactory)
        {
            _initialization = initialization;
        }

        public FactoryDialogResult(IViewModelFactory<T> viewModelFactory)
        {
            _viewModelFactory = viewModelFactory;
        }

        public void Execute(ActionExecutionContext context)
        {
            var vm = _viewModelFactory.Create();
            if (_initialization != null) _initialization(vm);
            bool? result = null;
            Caliburn.Micro.Execute.OnUIThread(() => result = IoC.Get<IWindowManager>().ShowDialog(vm));
            _viewModelFactory.Destroy(vm);
            OnCompleted(new ResultCompletionEventArgs { WasCancelled = !result.HasValue || result == false });
        }

        public event EventHandler<ResultCompletionEventArgs> Completed;

        protected void OnCompleted(ResultCompletionEventArgs args)
        {
            if (Completed != null) Completed(this, args);
        }
    }
}